<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/4/10
 * Time: 上午9:53
 */

namespace app\mobile\controller;


use app\common\model\Agent;
use app\common\model\CardJcList;
use app\common\model\CardJcLog;
use app\common\model\CardJcUserget;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardjc extends Mobilebase
{
    //商户计次卡列表
    public function cardjclist(Request $request){
        $arr = $request->param();
        if ($request->isAjax()) {
            $param = $request->post();
            $CardJcList = new CardJcList();
            $map['a.card_id']= $param['card_id'];
            $map['a.is_del']= 1;
            $list = $CardJcList->alias('a')
                ->join('wn_card_member b', 'a.card_id=b.card_id', 'left')
                ->where($map)->field('a.id,a.top_mid,a.mid,a.title,a.card_id,a.price,a.pay_num,a.store,a.rec_num,a.num,a.creat_time,a.term_of,b.logo_url,b.brand_name')->select();
            $cardcount = $CardJcList->alias('a')->where($map)->count('id');
            $page_num = ceil($cardcount / 5);
            if ($list) {
                if($page_num > (int)$param['page'] || $page_num == (int)$param['page']) {
                    $data['code'] = 0;
                    $data['message'] = 'SUCCESS';
                    $data['data'] = $list;
                    $data['count'] = $cardcount;
                    $data['page_num'] = $page_num;
                    $data['page'] = $param['page'];
                }else{
                    $data['code'] = 9002;
                    $data['data'] = '';
                    $data['message'] = 'error';
                    $data['page_num'] = $page_num;
                    $data['count'] = $cardcount;
                    $data['page'] = $param['page'];
                }
            }else{
                $data['code'] = 9002;
                $data['data'] = '';
                $data['message'] = 'error';
                $data['page_num'] = $page_num;
                $data['count'] = $cardcount;
                $data['page'] = $param['page'];
            }
            return json($data);
        }else {
            //JSSDK
            $CardMember = new CardMember();
            $info = $CardMember->where(['card_id'=>$arr['card_id']])->field('title,brand_name,card_id,logo_url')->find();
            $share['wxjssdk'] = $this->getsharejssdk($arr['card_id']);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //商户计次卡详情
    public function cardjcinfo(Request $request){

        $arr = $request->param();
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $openid = Session::get($appid . "_openid");

        $CardJcList = new CardJcList();
        $map['a.card_id'] = $arr['card_id'];
        $map['a.id'] = $arr['id'];
        $cardjc = $CardJcList->alias('a')
            ->join('wn_card_member b', 'a.card_id=b.card_id', 'left')
            ->where($map)->field('a.id,a.top_mid,a.mid,a.title,a.card_id,a.price,a.pay_num,a.store,a.rec_num,a.num,a.creat_time,a.term_of,b.logo_url,b.brand_name')->find();
        $cardjc['openid'] = $openid;
        $this->assign('card', $arr);
        $this->assign('info', $cardjc);

        $share['wxjssdk'] = $this->getsharejssdk($arr['card_id']);
        $share['wxjssdk'] = json_encode($share['wxjssdk']);
        $this->assign('share',$share);
        return $this->fetch();


    }

    //我的计次卡列表
    public function cardjcmy(Request $request){
        $arr = $request->param();
        $user = $this->getuserinfo($arr,1);

        if ($user) {
            if ($request->isAjax()) {

                $param = $request->post();

                $map['a.card_id'] = $param['card_id'];
                $map['a.openid'] = $param['openid'];
                $map['a.is_del']= 1;
                $CardJcUserget = new CardJcUserget();
                $list = $CardJcUserget->alias('a')
                    ->join('wn_card_member b', 'a.card_id=b.card_id', 'left')
                    ->join('wn_card_jc_list c', 'a.tims_id=c.id', 'left')
                    ->where($map)->field('a.id,a.mid,a.card_id,c.title,a.num,a.surplus_num,a.addtime,a.end_time,a.term_of,b.logo_url,b.brand_name')->select();
                $lists = [];
                foreach ($list as $k=>$v){
                    $lists[$k] = $v;
                    $lists[$k]['end_time'] = date('Y-m-d',$v['end_time']);
                }
                $cardcount = $CardJcUserget->alias('a')->where($map)->count('a.id');
                $page_num = ceil($cardcount / 5);
                if ($list) {
                    if($page_num > (int)$param['page'] || $page_num == (int)$param['page']) {
                        $data['code'] = 0;
                        $data['message'] = 'SUCCESS';
                        $data['data'] = $list;
                        $data['count'] = $cardcount;
                        $data['page_num'] = $page_num;
                        $data['page'] = $param['page'];
                    }else{
                        $data['code'] = 9002;
                        $data['data'] = '';
                        $data['message'] = 'error';
                        $data['page_num'] = $page_num;
                        $data['count'] = $cardcount;
                        $data['page'] = $param['page'];
                    }
                }else{
                    $data['code'] = 9002;
                    $data['data'] = '';
                    $data['message'] = 'error';
                    $data['page_num'] = $page_num;
                    $data['count'] = $cardcount;
                    $data['page'] = $param['page'];
                }
                return json($data);
            }else {
                $param = $request->param();
                $this->_init();
                $appid = $this->getappid($param['card_id']);
                $openid = Session::get($appid . "_openid");
                $CardMember = new CardMember();
                $param = $CardMember->where(['card_id'=>$arr['card_id']])->field('title,brand_name,card_id,logo_url')->find();
                $param['openid'] = $openid;
                $this->assign('info', $param);


                $share['wxjssdk'] = $this->getsharejssdk($param['card_id']);
                $share['wxjssdk'] = json_encode($share['wxjssdk']);
                $this->assign('share',$share);
                return $this->fetch();
            }
        }else{
            $this->redirect('carduser/index', ['card_id' => $arr['card_id']]);
        }
    }


    //用户付费
    public function pay(Request $request){
        $arr = $request->param();
        $this->_init();
        $info = $this->getuserinfo($arr,1);
        if ($request->isAjax()){
            $param = $request->post();
            if ($param['price'] > 0) {
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $config = $Merchant->where(array('id' => $param['mid']))->field('sub_mch_id,agent,wx_open_id')->find();
                $agent = $Agent->where(array('id' => $config['agent']))->field('partnerid,partnerkey,wx_open_id')->find();
                $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->field('authorizer_appid')->find();
                $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
                $options = array(
                    'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                    'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                    'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                );
//                return json($options);
                $weObj = new Wxobjopen($options);
                $price = $param['price'];
                $appid = $users['authorizer_appid'];
                $mch_id = $agent['partnerid'];
                $out_trade_no = $param['orderid'];
                $body = "购买次卡";
                $sub_mch_id = $config['sub_mch_id'];
                $sub_appid = $userwx['authorizer_appid'];
                $total_fee = $price * 100;
                $data['orderid'] = $out_trade_no;
                $data['mid'] = $param['mid'];
                $data['openid'] = $param['openid'];
                $data['pay_statu'] = 0;
                $data['pay_cate'] = 'pay';
                $data['price'] = $price;
                $data['yf_price'] = $price;
                $data['zk_price'] = $data['yf_price'] - $data['price'];
                $data['add_time'] = time();
                $data['attach'] = 'pur_cardjc';
                $Paylog = new Paylog();
                $Paylog->allowField(true)->save($data);
                //END
                $CardJcList = new CardJcList();
                $jcinfo = $CardJcList->where(['id'=>$param['tims_id']])->find();
                //END
                $datas['orderid'] = $out_trade_no;
                $datas['mid'] = $param['mid'];
                $datas['us_id'] = $info['id'];
                $datas['card_id'] = $info['card_id'];
                $datas['cardjc_id'] = $param['tims_id'];
                $datas['user'] = $info['nickname'];
                $datas['openid'] = $param['openid'];
                $datas['type'] = 1;
                $datas['num'] = $jcinfo['pay_num'];
                $datas['addtime'] = time();
                $datas['source'] = 'online';
                $datas['pay_fs'] = 0;
                $CardJcLog = new CardJcLog();
                $CardJcLog->save($datas);
                //END
                $sub_openid = $param['openid'];
                $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
                $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
                $nonce_str = $weObj->generateNonceStr();
                $partnerkey = $options['partnerkey'];
                $arrdata = array(
                    "appid" => $appid,
                    'sub_appid' => $sub_appid,
                    "mch_id" => $mch_id,
                    "sub_mch_id" => $sub_mch_id,
                    "nonce_str" => $nonce_str,
                    "body" => $body,
                    "out_trade_no" => $out_trade_no,
                    "total_fee" => $total_fee,
                    "spbill_create_ip" => $spbill_create_ip,
                    "notify_url" => $notify_url,
                    "sub_openid" => $sub_openid,
                    'trade_type' => 'JSAPI'
                );
                $pay_xml = $weObj->createWxPackageXmls($arrdata,$partnerkey);
                $pay_xml = $weObj->get_pay_id($pay_xml);
//                return json($pay_xml);
                if ($pay_xml['return_code'] == 'SUCCESS') {
                    $prepay_id = $pay_xml['prepay_id'];
                    $jsApiObj["appId"] = $appid;
                    $timeStamp = time();
                    $jsApiObj["timeStamp"] = "$timeStamp";
                    $jsApiObj["nonceStr"] = $nonce_str;
                    $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                    $jsApiObj["signType"] = "MD5";
                    $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                    //状态码
                    $jsApiObj['code'] = 0;
                } else {
                    $jsApiObj = ['code' => 9002, 'message' => '支付失败！'];
                }
            } else {
                $jsApiObj = ['code' => 9001, 'message' => '请输入正确的充值金额！'];
            }

            return json($jsApiObj);
        }else {

            $this->assign('user', $info);
            return $this->fetch();

        }
    }

    /*
    * 支付结束
    *
    */
    public function r_payover()
    {
        if (request()->isAjax()) {
            $request = request();
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $request->post('id');
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $request->post('orderid');
            $nonce_str = $weObj->generateNonceStr();
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
            $payorder_xml = $weObj->getPayNum($pay_xml);
            $orderno = $payorder_xml['transaction_id'];
            $pay_zt = $payorder_xml['trade_state'];
            if ($pay_zt == "SUCCESS") {
                $array = array('code' => 0, 'message' => "支付成功",'url'=>url('mobile/cardjc/orderinfo','orderid='.$out_trade_no));

            } else {
                $array = array('code' => 1, 'message' => "支付失败",'url'=>'');
            }
            return json($array);
        }
    }

    //计次核销
    public function cardjchx(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
//            $map['tims_id'] = $param['tims_id'];
//            $map['card_id'] = $param['card_id'];
            $map['a.openid'] = $param['openid'];
            $map['a.id'] = $param['id'];
            $CardJcUserget = new CardJcUserget();
            $CardJcList = new CardJcList();
            $CardJcLog = new CardJcLog();
            $userinfo = $CardJcUserget->alias('a')
                ->join('wn_card_user_get b', 'a.code=b.code', 'left')
                ->where($map)->field('a.card_id,a.mid,a.openid,a.id,a.tims_id,a.surplus_num,a.num,a.end_time,a.term_of,b.top_mid,b.nickname,a.us_id')->find();

            $cardinfo = $CardJcList->where(['id'=>$userinfo['tims_id']])->find();
            if (!empty($param['mid'])) {
                if ($cardinfo['hx_pass'] == MD5($param['password'])) {
                    $end_time = date('Y-m-d', $userinfo['end_time']) + 86399;
                    if ($userinfo['surplus_num'] > 0 || $end_time > time()) {
                        $res = $CardJcUserget->alias('a')->where($map)->setDec('surplus_num');
                        if ($res) {

                            $datas['mid'] = $param['mid'];
                            $datas['user_id'] = $userinfo['id'];
                            $datas['card_id'] = $userinfo['card_id'];
                            $datas['us_id'] = $userinfo['us_id'];
                            $datas['cardjc_id'] = $userinfo['tims_id'];
                            $datas['user'] = $userinfo['nickname'];
                            $datas['openid'] = $userinfo['openid'];
                            $datas['type'] = 2;
                            $datas['num'] = 1;
                            $datas['addtime'] = time();
                            $datas['pay_fs'] = 8;
                            $datas['source'] = 'online';
                            $CardJcLog->allowField(true)->save($datas);
                            //END
                            $data['code'] = 0;
                            $data['data'] = '';
                            $data['message'] = '核销成功';
                        } else {
                            $data['code'] = 9003;
                            $data['data'] = '';
                            $data['message'] = '核销失败';
                        }
                    } else {
                        $data['code'] = 9004;
                        $data['data'] = '';
                        $data['message'] = '已过期，或使用完';
                    }
                } else {
                    $data['code'] = 9005;
                    $data['data'] = '';
                    $data['message'] = '核销密码错误';
                }
            }else{
                $data['code'] = 9006;
                $data['data'] = '';
                $data['message'] = '请选择门店后核销';
            }
            return json($data);
        }else{
            $this->_init();
            $param = $request->param();
            $appid = $this->getappid($param['card_id']);
            $CardJcUserget = new CardJcUserget();
            $map['a.id'] = $param['id'];
            $map['a.openid'] = Session::get($appid . "_openid");
            $info = $CardJcUserget->alias('a')
                ->join('wn_card_member b', 'a.card_id=b.card_id', 'left')
                ->join('wn_card_jc_list c', 'a.tims_id=c.id', 'left')
                ->where($map)->field('a.openid,a.id,a.mid,a.card_id,c.title,a.num,a.surplus_num,a.addtime,a.end_time,a.term_of,b.logo_url,b.brand_name,c.store')->find();
            $this->assign('info',$info);
            $mas['id'] = ['in',$info['store']];
            $Merchant = new Merchant();
            $mach = $Merchant->where($mas)->field('id,merchant')->select();
            $this->assign('mach',$mach);
            $share['wxjssdk'] = $this->getsharejssdk($param['card_id']);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            return $this->fetch();
        }
    }

    //订单信息
    public function orderinfo(Request $request){
        $Paylog = new Paylog();
        $CardJcLog = new CardJcLog();
        $CardJclist = new CardJcList();
        $param = $request->param();
        $info = $Paylog->where(['orderid'=>$param['orderid']])->find();

        $map['orderid'] = $param['orderid'];
        $map['openid'] = $info['openid'];
        $loginfo = $CardJcLog->where($map)->field('card_id,cardjc_id')->find();
        $cardinfo = $CardJclist->where(['id'=>$loginfo['cardjc_id']])->field('title,pay_num')->find();
        $info['card_title'] = $cardinfo['title'];
        $info['pay_num'] = $cardinfo['pay_num'];
        $info['card_id'] = $loginfo['card_id'];
//        return json($loginfo);
        $this->assign('info',$info);
        $share['wxjssdk'] = $this->getsharejssdk($loginfo['card_id']);
        $share['wxjssdk'] = json_encode($share['wxjssdk']);
        $this->assign('share',$share);
        return $this->fetch();
    }


    //获取订单
    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }

    //分享jssdk
    /*
     * $card_id
     *
     */
    private function getsharejssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }


}